package com.yx.system.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yx.common.annotation.Log;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.system.entity.TdCategory;
import com.yx.system.entity.TdClassification;
import com.yx.system.service.TdCategoryService;
import net.sf.json.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 一级分类控制器
 */
@RestController
@RequestMapping("/sys/category")
public class TdCategoryController2 {

    @Autowired
    private TdCategoryService tdCategoryService;

    /**
     * 按ID查询分类
     *
     * @return
     */
    @RequestMapping("/findById/{id}")
    @RequiresPermissions("sys:category:findById")
    public R findById(@PathVariable("id") int id) {
        return R.ok().put("category", tdCategoryService.selectByPrimaryKey(id));
    }

    /**
     * 查询所有
     *
     * @param map
     * @return
     */
    @GetMapping("findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map) {
        Query query = new Query(map);
        Page<TdCategory> pageUtil = new Page<TdCategory>(query.getPage(), query.getLimit());
        Page<TdCategory> page = tdCategoryService.queryPageList(pageUtil, query);
        return R.ok().put("page", page);
    }

    /**
     * 查询所有
     * @return
     */
    @PostMapping("findAll")
    public R findAll() throws JSONException {
        List<TdCategory> list = tdCategoryService.queryAll();
        return R.ok().put("list",list);
    }


    /**
     * 新增或修改
     *
     * @return
     */
    @Log("新增或修改分类")
    @PostMapping("saveOrUpdate")
    @RequiresPermissions("sys:category:saveOrUpdate")
    public R saveOrUpdate(@RequestBody TdCategory tdCategory) {
        if (tdCategory.getId() == null) {
            tdCategory.setIsdelete(false);
            tdCategory.setCreatedate(new Date());
            tdCategoryService.insert(tdCategory);
        } else {
            tdCategoryService.updateByPrimaryKey(tdCategory);
        }
        return R.ok();
    }

    /**
     * 删除 (软删除)
     *
     * @return
     */
    @Log("删除分类")
    @RequestMapping("delete")
    @RequiresPermissions("sys:category:delete")
    public R delete(@RequestBody Integer[] ids) {
        for (int i =0;i<ids.length;i++) {
            int id = ids[i];
            TdCategory tdCategory = tdCategoryService.selectByPrimaryKey(id);
            tdCategory.setIsdelete(true);
            tdCategoryService.updateByPrimaryKey(tdCategory);
        }
        return R.ok();
    }
}
